<?php
/**
 * hook钩子触发短信发送
 */
namespace app\api\hook;

include_once ROOT_PATH.'vendor/alibabacloud/client/src/Functions.php';
include_once ROOT_PATH.'vendor/alibabacloud/client/autoload.php';
include_once ROOT_PATH.'vendor/clagiordano/weblibs-configmanager/src/ConfigManager.php';

//阿里云短信发送相关类 composer安装
//composer require alibabacloud/sdk

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;


class Sms
{

    function smsSend($sms)
    {
        $config = \config('alisms');
        /*if ($sms->event=='sellerlogin'){
            $template_code = $config['TemplateCode']['sellercode'];
        } else {
            $template_code = $config['TemplateCode']['code'];
        }*/

        $template_code = 'SMS_498100235';
        //$param = ['store_name'=>'测试门店名称','project_name'=>'测试项目名称','date'=>'测试日期','address'=>'测试地址'];
        $param = ['store_name'=>$sms->store_name,'project_name'=>$sms->project_name,'date'=>$sms->date,'address'=>$sms->address];

        return $this->sendMsg($sms->mobile,$param,$template_code);
    }

    /*function smsCheck($sms)
    {
    	return $this->sendMsg($sms->mobile,['code'=>$sms->code],'code');
    }*/


    //@mobile 手机号码
    //@param  短信发送参数
    //@template 短信发送模板编号key值
    private function sendMsg($mobile,$param,$template){

        $config = \config('alisms');

        if(empty($param)||!isset($config)||empty($config)){
            return false;
        }

        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessSecret'])
            ->regionId($config['regionId'])
            ->asGlobalClient();

        //$TemplateCode = isset($config['TemplateCode'][$template])?$config['TemplateCode'][$template]:$config['TemplateCode']['code'];

        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => $config['SignName'],
                        'TemplateCode' => $template,
                        'TemplateParam' => json_encode($param)
                    ],
                ])
                ->request();

            if($result->Code=="OK"){
                return true;
            }else{
                return false;
            }


        } catch (ClientException $e) {

            return false;
            //echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {

            return false;
            //echo $e->getErrorMessage() . PHP_EOL;
        }
    }

}